package com.xingcheng.discord.midjourney;

import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.utils.data.DataObject;

import java.util.List;

/**
 * @author xingchen
 * @version 1.0.0
 * @title EventMessageListener
 * @description
 * @create 2023/12/31 16:02
 **/
@Slf4j
public class EventMessageListener {

    private final List<EventHandle> eventHandles;


    public EventMessageListener(List<EventHandle> messageHandlers) {
        this.eventHandles = messageHandlers;
    }

    public void onMessage(DataObject raw) {
        MessageType messageType = MessageType.of(raw.getString("t"));
        if (messageType == null || MessageType.DELETE == messageType) {
            return;
        }
        DataObject data = raw.getObject("d");
        if (ignoreAndLogMessage(data, messageType)) {
            return;
        }
        for (EventHandle eventHandle : this.eventHandles) {
            eventHandle.handle(messageType, data);
        }
    }

    private boolean ignoreAndLogMessage(DataObject data, MessageType messageType) {
        if (MessageType.INTERACTION_SUCCESS == messageType || MessageType.INTERACTION_CREATE == messageType) {
            //用户点击modal 只返回messageId 和nonce
            return false;
        }
        String channelId = data.getString("channel_id");
        String guildId = data.getString("guild_id");
        log.info("channelId:{} - guildId:{}: ",channelId,guildId);
        String authorName = data.optObject("author").map(a -> a.getString("username")).orElse("System");
        log.info("{} - {}: {}", messageType.name(), authorName, data.opt("content").orElse(""));
        return false;
    }

}
